<?php

class authenticationActions extends sfActions {

    public function executeRegisterForm(sfWebRequest $request){
        $this->setLayout('register');
    }

    public function executeRegister(sfWebRequest $request){
      if(!$this->getUser()->isAuthenticated()){
        //cogemos valores del request
        $name             = $request->getParameter('name');
        $last_name        = $request->getParameter('last_name');
        $email            = $request->getParameter('email');
        $password         = $request->getParameter('password');
        $repeat           = $request->getParameter('repeat');
        //validaciones respectivas
        $vEmail = new sfValidatorEmail(array('required'=>true));
        $vString= new sfValidatorString(array('required'=>true));
        try{$vEmail->clean(strtolower(trim($email)));}
        catch(sfValidatorError $exc){return $this->redirect('@register_form');}
        try{$vString->clean(strtolower(trim($name)));}
        catch(sfValidatorError $exc){return $this->redirect('@register_form');}
        try{$vString->clean(strtolower(trim($last_name)));}
        catch(sfValidatorError $exc){return $this->redirect('@register_form');}
        if($password!=$repeat){return $this->redirect('@register_form');}
        /*convierto los espacios en blanco en + para que no suceda
         * algun error al usar el web-service   */
        /*
        $pfirt_name = str_replace(' ', '+', $name);
        $plast_name = str_replace(' ', '+', $last_name);
        $pemail     = str_replace(' ', '+', $email);*/

        try{
            $conection = Propel::getConnection();
            $conection->beginTransaction();
            //procedo a registrar al usuario en practil
            $lib = new myPractil();
            $url = $lib->url_pracil_registrar_user($name,$last_name,md5($password),$email,'1');
            //si la url se forma correctamente
            if($url!=null){
                 $respuesta_registrar = @file_get_contents($url);
                 if($respuesta_registrar === FALSE){
                     $conection->rollBack();
                     return sfView::ERROR;
                 }else{
                     $decode = json_decode($respuesta_registrar);
                     $codigo_respuesta = $decode->{'success'};
                     //si el registro en practil es correcto
                     if($codigo_respuesta){
                         $new_user = new Account();
                         $new_user->setPractilAccountId($decode->{'accountpk'});/* pk de practil */
                         $new_user->setAccountTypeId('2');/* tipo 2: lector */
                         $new_user->setInterests('');/* sin intereses */
                         $new_user->setSubscriptions('');/* sin suscripciones */
                         $new_user->setFavoriteArticles('');/* sin artìculos favoritos */
                         $new_user->save();
                         $conection->commit();                        
                         $this->send_mail_opinics($decode->{'stoken'},$email);
                         /* debe confirmar su cuenta para poder ingresar */
                         return sfView::SUCCESS;
                     }else{
                         if($decode->{'code'} =="p-10003"){
                              $respt =  array('firtname'=>$firt_name,'lastname'=>$last_name,'email'=>$email,'password'=>$password,'message' =>$this->getContext()->getI18N()->__('user.register_user.el e-mail ya se encuentra registrado!'));
                              $message_sign_in = $this->getUser()->setAttribute('message_sign_in',$respt);
                              $conection->rollBack();
                              $this->redirect('@homepage');
                         }else if($decode->{'code'} =="p-20009"){
                              $respt =  array('firtname'=>$firt_name,'lastname'=>$last_name,'email'=>$email,'password'=>$password,'message' =>$this->getContext()->getI18N()->__('user.register_user.el e-mail ya se encuentra asociado a una cuenta!'));
                              $message_sign_in = $this->getUser()->setAttribute('message_sign_in',$respt);
                              $conection->rollBack();
                              $this->redirect('@homepage');
                         }else{
                             $conection->rollBack();
                             return sfView::ERROR;
                         }
                     }
                 }
            }else{
                $conection->rollBack();
                return sfView::ERROR;
            }
        }catch (Exception $e){
        
            $conection->rollBack();
            return sfView::ERROR;
        }
      }
    }

    private function send_mail_opinics($token,$email){
        try{
             $message = $this->getMailer()->compose();
             $message->setSubject('(Practil) Confirmación de Cuenta Opinics');
             $message->setTo($email);
             $message->setFrom(array('cquevedo@esfera.pe' => 'Practil Mailing'));
             $html = $this->getPartial('mailing/registerConfirmation', array(
                'uri'=>sfConfig::get('app_url_opinics').'authentication/confirmation_account?token='.$token.'&email='.$email
             ));
             $message->setBody($html, 'text/html');
             $this->getMailer()->send($message);
             return true;
         }catch (Exception $e){
             return false;
         }

    }

    public function executeLogin(sfWebRequest $request){
        /* logueo con practil */
        $email          = $request->getParameter('email');
        $password       = $request->getParameter('password');

        $myPractil = new myPractil();
        $url = $myPractil->url_practil_login($email, $password);

        $login_resp = file_get_contents($url);
        $decode = json_decode($login_resp);

        if($decode->{'success'}){
            /* practil devuelve un id */
            /* busco ese id de practil en mi sistema */
            $c = new Criteria();
            $c->add(AccountPeer::PRACTIL_ACCOUNT_ID,$decode->{'pkaccount'});
            $account = AccountPeer::doSelectOne($c);
            if(is_object($account)){
                /* dump login to session */
                $this->loginToSession($account->getId(),'@homepage',$decode->{'name'},$decode->{'last_name'},$decode->{'email'});
            }else{
                $this->message = $decode->{'message'};
                $this->code= $decode->{'code'};
                return sfView::ERROR;
            }
        }else{
        //si el usuario existe pero no esta asociado a esta plataforma!
         if($decode->{'code'}=="p-10004"){
            $token = md5($decode->{'code'});
            $email = $email;
            $this->getUser()->setAttribute('s_pk_practil_associate_account',$decode->{'tokenpk'});
            $this->redirect('@asociate_account?token='.$token."&email=".$email);
                  echo "dasdad"       ;
          }else{
                $this->message = $decode->{'message'};
                $this->code= $decode->{'code'};
                return sfView::ERROR;
          }
          
        }
    }

    public function executeAsociateAccount(sfWebRequest $request){
            $this->setLayout('register');          
            $this->token=$request->getParameter('token');
            $this->email=$request->getParameter('email');            
    }


    public function executeAsociateAccountToPractil(sfWebRequest $request){
        $this->setLayout('register');
        $token = $request->getParameter('token-account');
        $pk_practil = $this->getUser()->getAttribute('s_pk_practil_associate_account',null);
        $email = $request->getParameter('email-account');

        if($token == md5('p-10004')){
           if($pk_practil!=null){
               $lib = new myPractil();
               $url= $lib->url_practil_associate_account($email);
               $respuesta_servicio = file_get_contents($url);
               $decode = json_decode($respuesta_servicio);
                   if($decode->{'success'}){
                         $new_user = new Account();
                         $new_user->setPractilAccountId($decode->{'accountpk'});/* pk de practil */
                         $new_user->setAccountTypeId('2');/* tipo 2: lector */
                         $new_user->setInterests('');/* sin intereses */
                         $new_user->setSubscriptions('');/* sin suscripciones */
                         $new_user->setFavoriteArticles('');/* sin artìculos favoritos */
                         $new_user->save();                          
                        return sfView::SUCCESS;
                   }else{
                        $this->getUser()->setAttribute('s_pk_practil_associate_account',null);
                        return sfView::ERROR;
                   }

           }else{
            $this->getUser()->setAttribute('s_pk_practil_associate_account',null);
            return sfView::ERROR;
           }
        }else{
           $this->getUser()->setAttribute('s_pk_practil_associate_account',null);
           return sfView::ERROR;
        }
            
    }

    /* mètodo para loguear al usuario y redirijirlo a la ùltima uri */
    private function loginToSession($suid_opinics,$uri='@homepage',$name="",$last_name="",$email=""){
        if(!$this->getUser()->isAuthenticated()){
            $this->getUser()->setAttribute('suid',$suid_opinics);
            $object = AccountPeer::retrieveByPK($suid_opinics);
            if(!is_object($object)){ $this->forward404(); }
            $array_attr = array();
            array_push($array_attr, $object->getPractilAccountId());/* 0 */
            array_push($array_attr, $object->getAccountTypeId());
            array_push($array_attr, $name);
            array_push($array_attr, $last_name);/* 3 */
            array_push($array_attr, $email);
            array_push($array_attr, $object->getInterests());/* 5 */
            array_push($array_attr, $object->getSubscriptions());
            array_push($array_attr, $object->getFavoriteArticles());
            array_push($array_attr, $object->getAccountType()->getDescription()); /* 8 */
            if($object->getInterests()==''){
                $this->getUser()->setAttribute('stmp1',true);
            }
            $this->getUser()->setAttribute('suattr',$array_attr);
            $this->getUser()->setAuthenticated(true);
            /* verificar si es autor o no */
            if($object->getAccountTypeId()=='1'){
                $this->getUser()->addCredential('author');
            }
            $this->redirect($uri);
        }
    }

    public function executeLogout(sfWebRequest $request){
        $this->getUser()->getAttributeHolder()->clear();
        $this->getUser()->setAuthenticated(false);
        $this->redirect('@loggedOut');
    }

    public function executeChangeLang(sfWebRequest $request){
        $lang = $request->getParameter('lang');
        $uri = $request->getParameter('uri');
        $original_culture = $this->getUser()->getCulture();
        $this->getUser()->setCulture($lang);
        $this->redirect(str_replace('/'.$original_culture.'/', '/'.$lang.'/', $uri));
    }

    public function executeChangeCountry(sfWebRequest $request){
        $country_id = $request->getParameter('country');
        $country = CountryPeer::retrieveByPK($country_id);
        $hduri = $request->getParameter('hduri');
        $this->getUser()->setAttribute('scountry',$country);
        $this->redirect($hduri);
    }

   public function executeConfirmation_account(sfWebRequest $request){
        $email          = $request->getParameter('email');
        $token_acount   = $request->getParameter('token');

        $lib = new myPractil();
        $url = $lib->url_practil_confirmation_account($email, $token_acount);
        $respuesta        = file_get_contents($url);
        $decode           = json_decode($respuesta);
        $codigo_respuesta = $decode->{'code'};

        if($codigo_respuesta=="j-1003"){
             $this->getUser()->setAttribute('ses_confirmacion',true);
             $this->redirect('authentication/success?email='.$email);
        }else{
             $this->getUser()->setAttribute('ses_confirmacion',false);
             $this->redirect('authentication/success?email='.$email);
        }  

   }

   public function executeSuccess(sfWebRequest $request){
           $this->setLayout('register');
           $email = $request->getParameter('email');
           $this->email = $email;
           $respuesta =  $this->getUser()->getAttribute('ses_confirmacion',false);
           if($respuesta){
               $this->getUser()->getAttributeHolder()->remove('ses_confirmacion');
               return sfView::SUCCESS;
           }else{
               $this->getUser()->getAttributeHolder()->remove('ses_confirmacion');
               return sfView::ERROR;
           }

   }



}